<template>
  <div class="w-full h-[64px] flex justify-between items-center pr-10">
    <div class="w-[300px] ml-6 flex justify-start items-center">
      <div @click="callBack" class="cursor-pointer">
        <span> <icon-left /> </span>
        <span class="ml-3 title">上传报告</span>
      </div>
    </div>
    <!-- <div class="flex-1">
      <a-row>
        <a-col :span="18">
          <a-steps :current="2">
            <a-step>资源包基础信息</a-step>
            <a-step>选择资源</a-step>
          </a-steps>
        </a-col>
      </a-row>
    </div> -->
  </div>
  <div class="w-full h-[700px] px-6">
    <div class="w-full h-full">
      <div>
        <a-row justify="start">
          <a-col :span="5" class="" v-if="route.query.action !== '查看详情'">
            <div class="w-full h-[64px] leading-[64px]">资产选择</div>
          </a-col>
          <a-col :span="19">
            <div class="w-full h-[64px] leading-[64px]">资产减值相关文件</div>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-row justify="space-between" :gutter="24">
          <a-col :span="5" class="" v-if="route.query.action !== '查看详情'">
            <div class="w-full h-[600px]">
              <div class="w-full h-full bg-white">
                <div class="mb-3">
                  <a-input-search
                    placeholder="请选择关键字搜索"
                    @search="handelSearch"
                    allow-clear
                    @clear="aaa"
                  />
                </div>
                <div class="flex items-center h-[32px] px-3 mb-2" v-if="selectNumber">
                  <span>已选择{{ selectNumber }}项</span>
                  <span class="ml-2 text-[#1459FA] cursor-pointer" @click="selectAll">取消</span>
                </div>
                <div class="w-full bg-white max-h-[600px]">
                  <div>
                    <a-table
                      bordered
                      :show-header="true"
                      :row-selection="TableRowSelectionData"
                      :columns="leftcolumns"
                      :data="leftdata"
                      @select="handleTableData"
                      @select-all="handleTableAll"
                      row-key="id"
                      :disabled="true"
                    ></a-table>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="19">
            <!-- <a-col :span="route.query.action == '查看详情' ? 24 : 19"> -->

            <div>
              <a-row>
                <a-col :span="19">
                  <div class="w-full bg-white max-h-[500px] overflow-auto mt-11">
                    <a-form-item label="上传类型">
                      <a-space>
                        <a-radio value="radio">上传文件</a-radio>
                        <a-radio value="disabled radio">上传数据</a-radio>
                      </a-space>
                    </a-form-item>
                    <a-form-item label="上传文件">
                    <a-upload draggable action="/" :default-file-list="fileList">
                      <template #upload-button>
                        <div class="upload-style">
                          <icon-cloud-download />
                          <div class="el-upload__text">点击或者拖动文件到虚线框内上传</div>
                          <div class="el-upload__type">支持扩展名：rar、zip、doc、docx、pdf、jpg…</div>
                        </div>
                      </template>

                    </a-upload>
                  </a-form-item>
                  </div>
                </a-col>
              </a-row>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue';
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();

/**
 * @method 表格配置
 */
import type { TableRowSelection } from '@arco-design/web-vue';
const TableRowSelectionData = ref<TableRowSelection>({
  type: 'checkbox', //行选择器的类型
  selectedRowKeys: [], //已选择的行（受控模式）
  defaultSelectedRowKeys: [], //默认已选择的行（非受控模式）
  showCheckedAll: true, //是否显示全选选择器
  title: '', //列标题
  width: undefined, //列宽度
  fixed: false, //是否固定
  checkStrictly: true, //是否开启严格选择模式
  onlyCurrent: false //是否仅展示当前页的 keys（切换分页时清空 keys）
});

/**
 * @method 表格数据
 */
import usetable from './use_hooks/useseletdata';
// const { leftcolumns, leftdata, rightcolumns } = usetable();
const { leftcolumns, rightcolumns } = usetable();
/**
 * @method 表格复选框逻辑
 */
const handleTableData = (rowKeys, rowKey, record) => {
  if (tabledata.value.length === 0) {
    TableRowSelectionData.value.selectedRowKeys = rowKeys;
    tabledata.value.push(record);
    return;
  }
  let found = false;
  tabledata.value.forEach((item, index) => {
    if (item.id === rowKey) {
      // 找到相同的 key，删除该条数据
      tabledata.value.splice(index, 1);
      TableRowSelectionData.value?.selectedRowKeys?.splice(index, 1);
      found = true; // 标记为找到匹配的 key
    }
  });
  // 如果没有找到相同的 key，则向数组中推入新记录
  if (!found) {
    TableRowSelectionData.value.selectedRowKeys = rowKeys;

    tabledata.value.push(record);
  }
};
/**
 * @method 表格全选
 */
const handleTableAll = (value) => {
  if (value == true) {
    let ids = leftdata.value.map((key) => key.id);
    TableRowSelectionData.value.selectedRowKeys = ids;
    leftdata.value.forEach((item) => tabledata.value.push(item));
    tabledata.value = tabledata.value.filter(
      (item, index, self) => index === self.findIndex((t) => t.name === item.name)
    );
  } else {
    TableRowSelectionData.value.selectedRowKeys = [];
    tabledata.value = [];
  }
};
const selectNumber = computed(() => TableRowSelectionData.value.selectedRowKeys?.length);
const selectAll = () => {
  TableRowSelectionData.value.selectedRowKeys = [];
  tabledata.value = [];
};
const tabledata = ref<Resource[]>([]);
import * as api from '@/api/pack/pack';
/**
 * @method 上一步
 */
const goBack = () => {
  const routeQuery = route.query as any; // 假设这是您的route的query对象
  const action = route.query.action;
  console.log(action);
  if (action == '资源编辑') {
    router.push({ name: '资源编辑', query: { ...routeQuery, action: '资源编辑' } });
  } else if (action == '资产更新') {
    router.push({ name: '资产更新', query: { ...routeQuery, action: '资产更新' } });
  } else {
    router.push({ name: '资产打包', query: { ...routeQuery } });
  }
};
/**
 * @method 选择下一步,资产打包创建
 */
const handleNext = async () => {
  const routeQuery = route.query as any; // 假设这是您的route的query对象
  routeQuery.shared = parseInt(routeQuery.shared as unknown as string);
  const resource_id = tabledata.value.map((item) => parseInt(item.id as unknown as string));
  console.log(resource_id);
  if (resource_id.length == 0) {
    Message.error('请选择资源');
    return;
  }
  routeQuery.resource_id = resource_id;
  const creatTypeData = {
    ...routeQuery,
    start_time: routeQuery.time[0],
    end_time: routeQuery.time[1],
    id: parseInt(routeQuery.id as unknown as string)
  };

  creatTypeData.owner_org_code = creatTypeData.owner_org_code.map((code) => parseInt(code));
  creatTypeData.resources = [];
  const action = route.query.action;
  switch (action) {
    case '资产打包':
      // 执行查看操作的代码
      await api.Create(creatTypeData);
      break;
    case '资源编辑':
      await api.Edit(creatTypeData);
      break;
    case '资产更新':
      await api.Update(creatTypeData);
      break;
  }
  Message.success('打包成功');
  router.push({ name: '资产管理' });
};
/**
 * @method 取消
 */
const callBack = () => {
  router.push({ name: '资产管理' });
};
/**
 * @method 去编辑
 */
const handleEdit = () => {
  // router.push({ name: '资源编辑', query: { id: record.id } });
};
/**
 * @method 初始化拉取目录数据
 */
interface Resource {
  code: string;
  create: string;
  created_time: string;
  data_browsing_number: number;
  data_call_number: number;
  data_download_number: number;
  data_fields_count: number;
  data_update_time: string;
  from: string;
  id: number;
  is_root: number;
  name: string;
  owner_org_code: any[];
  production_resource: string;
  scene: string[];
  security_level: string;
  sync_consanguinity: boolean;
  update_frequency: string;
  update_time: string;
  version: number;
}
const leftdata = ref<Resource[]>([]);
const page = ref({
  page: 1,
  page_size: 30,
  name: ''
});
const getProjectList = async () => {
  let res = await api.getProjectList(page.value);
  console.log(res.data);
  leftdata.value = res.data;
};
const handelSearch = (value) => {
  page.value.name = value;
  getProjectList();
};
const aaa = () => {
  page.value.name = '';
  getProjectList();
};
/**
 * @method 找到已经选择的东西
 */
const findElement = async () => {
  console.log(route.query);
  let res = await api.getDetails(route.query.id as any);
  const arr1 = res.data.resources;
  arr1.forEach((arr) => {
    leftdata.value.forEach((item) => {
      if (arr.code == item.code) {
        TableRowSelectionData.value.selectedRowKeys?.push(item.id);
        tabledata.value.push(item);
      }
    });
  });
};

onMounted(() => {
  const action = route.query.action;
  console.log(action);
  const arr1 = route.query.resources as unknown as Resource[];
  switch (action) {
    case '资产打包':
      // 执行查看操作的代码
      getProjectList(); //初始化拉取目录数据
      break;
    case '查看详情':
      // 执行查看操作的代码
      tabledata.value = arr1;
      break;
    case '资源编辑':
      (async () => {
        await getProjectList(); // 初始化拉取目录数据
        findElement(); // 等待 getProjectList() 完成后执行 findElement()
      })();
      break;
    case '资产更新':
      (async () => {
        await getProjectList(); // 初始化拉取目录数据
        findElement(); // 等待 getProjectList() 完成后执行 findElement()
      })();
  }
});
</script>

<style lang="less" scoped>
.title {
  font-family: Microsoft YaHei;
  font-size: 20px;
  font-weight: bold;
  line-height: 32px;
  letter-spacing: 0em;
  color: #394d73;
}
:deep(.arco-table-tr) {
  height: 30px;
}

.fotter {
  height: 64px;
  position: fixed;
  left: 220px;
  bottom: 0px;
  width: calc(100vw - 220px);
  color: white;
  text-align: center;
  padding: 10px;
  box-shadow: 0px 0px 6px 0px rgba(57, 77, 115, 0.1);
}
</style>
